﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GeoWeb.Common;
using System.Text;
using GeoWeb.DataContext;

namespace GeoWeb.Demo.ButtonConfigInfo
{
    /// <summary>
    /// ButtonInfo 的摘要说明
    /// </summary>
    public class ButtonInfo : IHttpHandler
    {
        //按钮功能数据库操作类
        ButtonInfoDal ButtonDal = new ButtonInfoDal();
        MenuTreeDal MenuDal = new MenuTreeDal();
        MenuTreeChildNodesDal menuChildDal = new MenuTreeChildNodesDal();
        //指定操作类型
        private string sType = string.Empty;

        public void ProcessRequest(HttpContext context)
        {
            string sMessage = "{\"state\":false}";

            if (GetParms(context))
            {
                switch (sType)
                {
                    case "getall"://获取所有的按钮
                        sMessage = GetListToJson();
                        break;
                    case "addbtn"://添加按钮操作
                        sMessage = AddButtonInfo(context);
                        break;
                    case "getsingle"://获取单一的按钮操作
                        sMessage = GetSingleeButton(context);
                        break;
                    case "savebtn"://修改一条记录
                        sMessage = UpdateButtonInfo(context);
                        break;
                    case "deletesingle"://删除一条记录
                        sMessage = DeleteSingleeButton(context);
                        break;
                    case "getsearch"://根据关键词查询
                        sMessage = GetSearchButton(context);
                        break;
                    case "getMenu"://查找菜单
                        sMessage = GetMenu(context);
                        break;
                    case "getMenu2"://查找菜单2
                        sMessage = GetMenu2(context);
                        break;
                    case "SaveMenuBtn"://保存菜单按钮
                        sMessage = SaveMenuBtn(context);
                        break;
                    case "getMenuButtonList"://获取菜单按钮
                        sMessage = GetMenuButtonList(context);
                        break;
                    default:
                        break;
                }
            }
            context.Response.Clear();
            context.Response.Write(sMessage);
            context.Response.End();
        }

        #region 获取所有的参数的方法
        /// <summary>
        /// 获取所有的参数的方法
        /// </summary>
        /// <returns></returns>
        public bool GetParms(HttpContext context)
        {
            bool state = true;

            sType = context.Request.Params["stype"];

            return state;
        }
        #endregion

        #region 获取所有的按钮列表并转换成JSON格式
        /// <summary>
        /// 获取所有的按钮列表并转换成JSON格式
        /// </summary>
        /// <returns></returns>
        public string GetListToJson()
        {
            string Result = "{\"state\":@state,\"rows\":@rows}";

            JsonHelper Json = new JsonHelper();
            StringHelper sHelper = new StringHelper();
            List<GeoButtonInfo> list = ButtonDal.GetButtonList();

            foreach (GeoButtonInfo entity in list)
            {
                entity.Name = HttpUtility.JavaScriptStringEncode(entity.Name);
                entity.Description = HttpUtility.JavaScriptStringEncode(entity.Description);
                entity.ButtonHTML = HttpUtility.JavaScriptStringEncode(entity.ButtonHTML);
                entity.JavaScript = HttpUtility.JavaScriptStringEncode(entity.JavaScript);
            }

            if (list.Count > 0)
            {
                Result = Result.Replace("@state", "true").Replace("@rows", Json.ObjectToJSON(list));
            }
            else
            {
                Result = Result.Replace("@state", "false").Replace("@rows", "[]");
            }
            return Result;
        }
        #endregion

        #region 添加按钮
        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string AddButtonInfo(HttpContext context)
        {
            string Result = "{\"state\":false}";

            StringHelper sHelper = new StringHelper();
            GeoButtonInfo buttoninfo = new GeoButtonInfo();

            buttoninfo.Name = sHelper.UrlDecode(context.Request.Params["bname"]);
            buttoninfo.Description = sHelper.UrlDecode(context.Request.Params["bdesc"]);
            buttoninfo.ButtonHTML = sHelper.UrlDecode(context.Request.Params["bhtml"]);
            buttoninfo.JavaScript = sHelper.UrlDecode(context.Request.Params["bjava"]);
            buttoninfo.ID = ButtonDal.GetMaxID() + 1;
            buttoninfo.ButtonID = Guid.NewGuid();

            if (ButtonDal.AddButtonInfo(buttoninfo) > 0)
            {
                Result = "{\"state\":true,\"bid\":\"" + buttoninfo.ID.ToString() + "\",\"bguid\":\"" + buttoninfo.ButtonID.ToString() + "\"}";
            }

            return Result;
        }
        #endregion

        #region 获取单个按钮的信息
        /// <summary>
        /// 获取单个按钮的信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSingleeButton(HttpContext context)
        {
            string Result = "{\"state\":false}";

            string buttonID = context.Request.Params["bguid"];
            if (!string.IsNullOrEmpty(buttonID))
            {
                GeoButtonInfo entity = ButtonDal.GetButtonByBtnID(buttonID);

                if (entity != null)
                {
                    StringHelper sHelper = new StringHelper();
                    Result = "{\"state\":true,\"bid\":\"" + entity.ID.ToString() + "\",\"bguid\":\"" + entity.ButtonID.ToString() + "\",\"desc\":\"" +
                        HttpUtility.JavaScriptStringEncode(entity.Description) + "\",\"html\":\"" + HttpUtility.JavaScriptStringEncode(entity.ButtonHTML) + "\",\"java\":\"" +
                        HttpUtility.JavaScriptStringEncode(entity.JavaScript) + "\",\"name\":\"" + HttpUtility.JavaScriptStringEncode(entity.Name) + "\"}";
                }
            }

            return Result;
        }
        #endregion

        #region 修改单条按钮记录的方法
        /// <summary>
        /// 修改单条按钮记录的方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string UpdateButtonInfo(HttpContext context)
        {
            string Result = "{\"state\":false}";

            StringHelper sHelper = new StringHelper();
            GeoButtonInfo buttoninfo = new GeoButtonInfo();

            buttoninfo.Name = sHelper.UrlDecode(context.Request.Params["bname"]);
            buttoninfo.Description = sHelper.UrlDecode(context.Request.Params["bdesc"]);
            buttoninfo.ButtonHTML = sHelper.UrlDecode(context.Request.Params["bhtml"]);
            buttoninfo.JavaScript = sHelper.UrlDecode(context.Request.Params["bjava"]);
            buttoninfo.ID = Convert.ToInt32(context.Request.Params["bid"]);
            buttoninfo.ButtonID = new Guid(context.Request.Params["bguid"]);

            if (ButtonDal.UpdateButtonInfo(buttoninfo) > 0)
            {
                Result = "{\"state\":true}";
            }

            return Result;
        }
        #endregion

        #region 删除单个按钮的信息
        /// <summary>
        /// 删除单个按钮的信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string DeleteSingleeButton(HttpContext context)
        {
            string Result = "{\"state\":false}";

            string buttonID = context.Request.Params["bguid"];
            if (!string.IsNullOrEmpty(buttonID))
            {
                if (ButtonDal.DeleteButtonInfo(buttonID) > 0)
                {
                    Result = "{\"state\":true}";
                }
            }

            return Result;
        }
        #endregion

        #region 根据关键字查询相关的按钮信息
        /// <summary>
        /// 根据关键字查询相关的按钮信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSearchButton(HttpContext context)
        {
            string Result = "{\"state\":false}";

            string KeyWords = context.Request.Params["keywds"];

            if (!string.IsNullOrEmpty(KeyWords))
            {
                JsonHelper Json = new JsonHelper();
                StringHelper sHelper = new StringHelper();
                List<GeoButtonInfo> list = ButtonDal.GetButtonListBySearch(KeyWords);

                foreach (GeoButtonInfo entity in list)
                {
                    entity.Name = HttpUtility.JavaScriptStringEncode(entity.Name);
                    entity.Description = HttpUtility.JavaScriptStringEncode(entity.Description);
                    entity.ButtonHTML = HttpUtility.JavaScriptStringEncode(entity.ButtonHTML);
                    entity.JavaScript = HttpUtility.JavaScriptStringEncode(entity.JavaScript);
                }

                if (list.Count > 0)
                {
                    Result = "{\"state\":true,\"rows\":" + Json.ObjectToJSON(list) + "}";
                }
            }

            return Result;
        }
        #endregion
        #region 菜单数据
        /// <summary>
        /// 菜单数据
        /// </summary>
        /// <returns></returns>
        public string GetMenu(HttpContext context)
        {
            string Result = "{\"state\":false}";
            Result = "{\"state\":true,\"rows\":" + getMenuJSON(null,context) + "}";
            return Result;
        }
        public string GetMenu2(HttpContext context)
        {
            string Result = "{\"state\":false}";
            string TreeID= context.Request.Params["TreeID"];
            if (!string.IsNullOrEmpty(TreeID))
            {
                GeoMenuTree entity= MenuDal.Select(new Guid(TreeID));
                Result = "[{'name':'" + entity.MenuTreeName + "','OID':'" + entity.MenuTreeOID + "','open':true,'children':" + getMenuJSON(TreeID, context) + "}]";
                Result = "{\"state\":true,\"rows\":" + Result + "}"; 
            }
            return Result;
        }
        /// <summary>
        /// 递归获取菜单
        /// </summary>
        /// <param name="id">菜单主键</param>
        /// <returns></returns>
        private string getMenuJSON(object id, HttpContext context)
        {
            string Result = "[]";
            string MenuTop = context.Request.Params["MenuTop"];//是否只查询顶级菜单
            List<GeoMenuTree> list = (id==null) ? MenuDal.GetMenuTreeList() : MenuDal.GetMenuTreeList(new Guid(id.ToString()));
            if (list != null&&list.Count>0)
            {
                Result = "[";
                for (int i = 0; i < list.Count; i++)
                {
                    if (i > 0)
                    {
                        Result += ",";
                    }
                    GeoMenuTree entity = list[i];
                    Result += "{";
                    Result += "'name':'" + HttpUtility.JavaScriptStringEncode(entity.MenuTreeName)+"'";
                    Result += ",'OID':'"+entity.MenuTreeOID.ToString()+"'";
                    //是否绑定跳转URL
                    if (!string.IsNullOrEmpty(context.Request.Params["ShowUrl"])&&!string.IsNullOrEmpty(entity.url))
                    {
                        string UrlStr=entity.url;
                        string[] str_Arry=entity.url.Split('?');
                        if (str_Arry.Length > 1)
                            UrlStr += "&configNodeId=" + entity.MenuTreeOID.ToString();
                        else
                            UrlStr += "?configNodeId=" + entity.MenuTreeOID.ToString();
                        Result += ",'url':'" + UrlStr + "'";
                        Result += ",'target':'DemoContext'";
                    }//是否显示图片 
                    if (!string.IsNullOrEmpty(context.Request.Params["ShowIcon"]) && !string.IsNullOrEmpty(entity.icon))
                    {
                        Result += ",'icon':'" + entity.icon + "'";
                    }//是否只查询顶级菜单
                    if (string.IsNullOrEmpty(MenuTop))
                    {
                        string nodes = getMenuJSON(entity.MenuTreeOID, context);
                        if (nodes != "")
                        {
                            Result += ",'open': true,'children':" + nodes;
                        }
                    }
                    Result += "}";
                }
                Result += "]";
            }
            return Result;
        }
        /// <summary>
        /// 保存菜单按钮
        /// </summary>
        /// <returns></returns>
        public string SaveMenuBtn(HttpContext context)
        {
            string Result = "{\"state\":false}";
            string TreeID = context.Request.Params["TreeID"];
            string btnIDs = context.Request.Params["btnIDs"];
            int ResultInt = 0;
            if (TreeID != null) {
               GeoConfigTreeChildNodes entity= menuChildDal.select(TreeID);
               if (entity != null && entity.NodesGuid == TreeID)
               {
                   entity.ButtonInfo = btnIDs;
                   GeoWeb.DataContext.Field[] field_arry = { GeoConfigTreeChildNodes._.NodesGuid, GeoConfigTreeChildNodes._.ButtonInfo };
                   object[] value_Arry = { entity.NodesGuid, entity.ButtonInfo };
                   ResultInt = menuChildDal.UpdateEntity(entity, field_arry, value_Arry, GeoConfigTreeChildNodes._.NodesGuid == entity.NodesGuid);
               }
               else {
                   entity = new GeoConfigTreeChildNodes();
                   entity.NodesGuid = TreeID;
                   entity.ButtonInfo = btnIDs;
                   ResultInt=menuChildDal.AddEntity(entity);
               }
            }
            if (ResultInt > 0) {
                Result = "{\"state\":true,\"rows\":" + ResultInt + "}";
            }
            return Result;
        }
        /// <summary>
        /// 根据菜单ID获取该菜单的按钮数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetMenuButtonList(HttpContext context)
        {
            string Result = "{\"state\":true,rows:[]}";
            string TreeID = context.Request.Params["TreeID"];
            if(!string.IsNullOrEmpty(TreeID)){
                GeoMenuTree menuEntity= MenuDal.Select(new Guid(TreeID));
                if (menuEntity != null)
                {
                    List<GeoButtonInfo> list = menuChildDal.GetPageButton(TreeID);
                    if (list.Count > 0)
                    {
                        JsonHelper Json = new JsonHelper();
                        Result = "{\"state\":true,\"MenuName\": \""+menuEntity.MenuTreeName+"\" , \"rows\":" + Json.ObjectToJSON(list) + "}";
                    }
                }
            }
            return Result;
        }

        #endregion
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}